#!/bin/bash

set -e -o pipefail

./bin/kubectl create namespace spire
./bin/kubectl create secret -n spire generic vault-tls \
              --from-file=vault_ca.pem=vault_ca.pem

# Verify AppRole Auth
log-info "verifying approle auth..."
APPROLE_ID=$(./bin/kubectl exec -n vault vault-0 -- vault read --format json auth/approle/role/spire/role-id | jq -r .data.role_id)
SECRET_ID=$(./bin/kubectl exec -n vault vault-0 -- vault write --format json -f auth/approle/role/spire/secret-id | jq -r .data.secret_id)
./bin/kubectl create secret -n spire generic vault-credential \
              --from-literal=approle_id=$APPROLE_ID \
              --from-literal=secret_id=$SECRET_ID 
./bin/kubectl apply -k ./conf/server/approle-auth
./bin/kubectl wait pods -n spire -l app=spire-server --for condition=Ready --timeout=60s
./bin/kubectl delete -k ./conf/server/approle-auth
./bin/kubectl delete secret -n spire vault-credential
./bin/kubectl wait pods -n spire -l app=spire-server --for=delete --timeout=60s

# Verify K8s Auth
log-info "verifying k8s auth..."
./bin/kubectl apply -k ./conf/server/k8s-auth
./bin/kubectl wait pods -n spire -l app=spire-server --for condition=Ready --timeout=60s
./bin/kubectl delete -k ./conf/server/k8s-auth
./bin/kubectl wait pods -n spire -l app=spire-server --for=delete --timeout=60s

# Verify Cert Auth
log-info "verifying cert auth..."
./bin/kubectl create secret -n spire generic vault-credential \
              --from-file=client.pem=client.pem \
              --from-file=client_key.pem=client_key.pem
./bin/kubectl apply -k ./conf/server/cert-auth
./bin/kubectl wait pods -n spire -l app=spire-server --for condition=Ready --timeout=60s
./bin/kubectl delete -k ./conf/server/cert-auth
./bin/kubectl delete secret -n spire vault-credential
./bin/kubectl wait pods -n spire -l app=spire-server --for=delete --timeout=60s

# Verify Token Auth
log-info "verifying token auth..."
TOKEN=$(./bin/kubectl exec -n vault vault-0 -- vault token create -policy=spire -ttl=1m -field=token)
./bin/kubectl create secret -n spire generic vault-credential \
              --from-literal=token=$TOKEN
./bin/kubectl apply -k ./conf/server/token-auth
./bin/kubectl wait pods -n spire -l app=spire-server --for condition=Ready --timeout=60s
